<template xmlns:dict-tag="http://www.w3.org/1999/html">
  <div class="app-container">
    <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" v-show="showSearch" label-width="68px">
      <el-form-item label="客户编号" prop="sn">
        <el-input
          v-model="queryParams.sn"
          placeholder="请输入客户编号"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="客户名称" prop="name">
        <el-input
          v-model="queryParams.name"
          placeholder="请输入客户名称"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="el-icon-plus"
          size="mini"
          @click="handleAdd"
          v-hasPermi="['mes:cust_info:add']"
        >新增客户</el-button>
      </el-col>
      <el-col :span="1.5">
      <el-button
        type="warning"
        plain
        icon="el-icon-download"
        size="mini"
        @click="handleExport"
        v-hasPermi="['mes:mater_plan:export']"
      >导出</el-button>
      </el-col>
<!--      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>-->
    </el-row>

    <el-table v-loading="loading" :data="cust_infoList" border style="width: 100%" @selection-change="handleSelectionChange">
<!--      <el-table-column type="selection" width="55" align="center" />-->
      <el-table-column label="序号" align="center" width="55" prop="number"/>
      <el-table-column label="客户状态" align="center" prop="state" width="90" >
        <template v-slot = "scope">
          <dict-tag :options="dict.type.customer_state" :value="scope.row.state"/>
        </template>
      </el-table-column>
      <el-table-column label="客户编号" align="center" prop="sn" />
      <el-table-column label="客户名称" align="center" prop="name" />
      <el-table-column label="客户等级" align="center" prop="grade">
        <template v-slot = "scope">
          <dict-tag :options="dict.type.customer_grade" :value="scope.row.grade"/>
        </template>
      </el-table-column>
      <el-table-column label="创建者" align="center" prop="createdBy" />
      <el-table-column label="创建时间" align="center" prop="createdTime" width="180">
        <template slot-scope="scope">
          <span>{{ parseTime(scope.row.createdTime, '{y}-{m}-{d}') }}</span>
        </template>
      </el-table-column>
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
        <template slot-scope="scope">
          <el-button
            size="mini"
            type="text"
            icon="el-icon-edit"
            @click="handleUpdate(scope.row)"
            v-hasPermi="['mes:cust_info:edit']"
          >修改</el-button>
          <el-button
            size="mini"
            type="text"
            :icon="scope.row.state === 0 ? 'el-icon-check' : 'el-icon-close'"
            @click="toggleStatus(scope.row)"
          >
            {{ scope.row.state === 0 ? '停用' : '启用' }}
          </el-button>
          <el-button
            size="mini"
            type="text"
            icon="el-icon-delete"
            @click="handleDelete(scope.row)"
            v-hasPermi="['mes:cust_info:remove']"
          >删除</el-button>
        </template>
      </el-table-column>
    </el-table>

    <pagination
      v-show="total>0"
      :total="total"
      :page.sync="queryParams.pageNum"
      :limit.sync="queryParams.pageSize"
      @pagination="getList"
    />

    <!-- 添加或修改客户管理对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="500px" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="80px">
        <el-form-item label="客户名称" prop="name">
          <el-input v-model="form.name" placeholder="请输入客户名称" style="width: 60%;"/>
        </el-form-item>
        <el-form-item label="客户等级" prop="grade">
          <el-select v-model="form.grade" placeholder="请选择客户等级" style="width: 60%">
            <el-option
              v-for="option in dict.type.customer_grade"
              :key="option.value"
              :label="option.label"
              :value="option.value"
            ></el-option>
          </el-select>
        </el-form-item>

        <el-form-item label="客户状态" prop="state">
          <el-select v-model="form.state" placeholder="请选择客户状态" style="width: 60%">
            <el-option
              v-for="option in dict.type.customer_state"
              :key="option.value"
              :label="option.label"
              :value="option.value"
            ></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="联系人" prop="contact">
          <el-input v-model="form.contact" placeholder="请输入联系人" style="width: 60%;"/>
        </el-form-item>
        <el-form-item label="联系电话" prop="contactNumber">
          <el-input
            v-model.trim="form.contactNumber"
            placeholder="请输入联系电话"
            maxlength="11"
            @blur="validateContactNumber"
            style="width: 60%;"
          />
        </el-form-item>
        <el-form-item label="联系地址" prop="address">
          <el-input v-model="form.address" type = "textarea" placeholder="请输入地址" style="width: 60%;"/>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确定</el-button>
        <el-button @click="cancel">取消</el-button>
      </div>
    </el-dialog>

  </div>
</template>

<script>
import { listCust_info, getCust_info, delCust_info, addCust_info, updateCust_info } from "@/api/mes/cust_info";

export default {
  name: "Cust_info",
  dicts:["customer_grade","customer_state"],
  data() {
    return {
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 客户管理表格数据
      cust_infoList: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        sn: null,
        name: null,
      },
      // 表单参数
      form: {
        id: null,
        sn: null,
        name: null,
        contact:null,
        contactNumber:null,
        address:null,
        grade: null,
        state: null,
        isDeleted: null,
        createdBy: null,
        createdTime: null,
        updatedBy: null,
        updatedDate: null,
        remark: null,
      },
      // 表单校验
      rules: {
        name: [
          { required: true, message: "客户名称不能为空", trigger: "blur" }
        ],
        grade:[
          { required: true, message: "客户等级必须选择", trigger: "change" }
        ],
        state:[
          { required: true, message: "客户状态必须选择", trigger: "change" }
        ],
        contactNumber:[{
          required:true,message:"联系电话不能为空"
        }],
        contact:[
          { required: true, message: "联系人不能为空", trigger: "blur" }
        ],
        address:[
          { required: true, message: "地址不能为空", trigger: "blur" }
        ],
      },
    };
  },
  created() {
    this.getList();
  },
  methods: {
    /** 查询客户管理列表 */
    getList() {
      this.loading = true;
      listCust_info(this.queryParams).then(response => {
        this.cust_infoList = response.rows;
        this.total = response.total;
        this.loading = false;
        this.calculateIndex(); // 手动计算序号
      });
    },
    /** 列表编号 */
    calculateIndex() {
      this.cust_infoList.forEach((item, index) => {
        this.$set(item, 'number', index + 1);
      });
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },
    // 表单重置
    reset() {
      this.form = {
        id: null,
        sn: null,
        name: null,
        grade: null,
        state: null,
        isDeleted: null,
        createdBy: null,
        contact:null,
        contactNumber:null,
        address:null,
        createdTime: null,
        updatedBy: null,
        updatedDate: null,
        remark: null
      };
      this.resetForm("form");
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm");
      this.handleQuery();
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.id)
      this.single = selection.length!==1
      this.multiple = !selection.length
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset();
      this.open = true;
      this.title = "新增客户信息";
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset();
      const id = row.id || this.ids
      getCust_info(id).then(response => {
        this.form = response.data;
        this.convertData();  // 调用转换函数
        this.open = true;
        this.title = "修改客户信息";
        console.log('选中的客户状态值:', this.form.grade);
      });
    },
    /** 提交按钮 */
    submitForm() {
      this.$refs["form"].validate(valid => {
        if (valid) {
          this.prepareFormData();  // 调用转换函数
          if (this.form.id != null) {
            updateCust_info(this.form).then(response => {
              this.$modal.msgSuccess("修改成功");
              this.open = false;
              this.getList();
            });
          } else {
            addCust_info(this.form).then(response => {
              this.$modal.msgSuccess("新增成功");
              this.open = false;
              this.getList();
            });
          }
        }
      });
    },
    /** 切换状态按钮操作 */
    toggleStatus(row) {
      const newState = row.state === 0 ? 1 : 0;
      // 更新用户状态
      updateCust_info({ id: row.id, state: newState }).then(response => {
        this.$modal.msgSuccess("停用成功");
        this.getList();
      }).catch(() => {
        this.$modal.msgError("停用失败，请稍后再试");
      });
    },
    /** 联系电话验证*/
    validateContactNumber(event) {
      const value = event.target.value;
      // 如果不是纯数字或者长度不为11，清空输入框的值
      if (!/^\d{11}$/.test(value)) {
        this.form.contactNumber = '';
        this.$message.error("联系电话必须是11位数字");
      }
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const ids = row.id || this.ids;
      const name = row.name || this.name;
      this.$modal.confirm('是否确认删除客户名称为"' + name + '"的数据项？').then(function() {
        return delCust_info(ids);
      }).then(() => {
        this.getList();
        this.$modal.msgSuccess("删除成功");
      }).catch(() => {});
    },
    /** 数据转换函数 */
    convertData() {
      if (this.form.grade !== null) {
        this.form.grade = this.form.grade.toString();
      }
      if (this.form.state !== null) {
        this.form.state = this.form.state.toString();
      }
    },
    /** 表单数据转换函数 */
    prepareFormData() {
      if (this.form.grade !== null) {
        this.form.grade = parseInt(this.form.grade);
      }
      if (this.form.state !== null) {
        this.form.state = parseInt(this.form.state);
      }
    },
    /** 导出按钮操作 */
    handleExport() {
      this.download('mes/cust_info/export', {
        ...this.queryParams
      }, `cust_info_${new Date().getTime()}.xlsx`)
    },
  },
};
</script>
